// 安全拦截器
const jwt = require("jsonwebtoken");
/**
 * 验证权限
 * @param token
 * @param secretkey 秘钥
 * @param success
 * @param error
 */
function verify (token,secretkey,success,error){
    jwt.verify(token,secretkey,function(err,decode){
        if(err){
            if (error) {
                error(err);
            }
        }else{
            if (success) {
                success(decode);
            }
        }
    })
}

function verifysync (token,secretkey){
    return new Promise((resolve,reject) =>{
        jwt.verify(token,secretkey,function(err,decode){
            if(err){
                console.log(err.message)
                resolve({err:'error',msg:'会话已过期，请重新登录'})
                } else{
                resolve(decode)
            }
        })
    })
}
/**
 * 签名
 * @param load 载荷 json对象 存储存在
 * @param secretkey 秘钥
 * @param expiresIn 过期时间 秒
 * @returns {number | PromiseLike<ArrayBuffer>}
 */
function sign (load,secretkey,expiresIn) {
    var token = jwt.sign(load,secretkey,{expiresIn: expiresIn});
    return token;
}
//load代表载荷即用户对象(密码被清)，secretkey密钥，expiresIn过期时间，单位为秒
module.exports = {verify,sign,verifysync};
/*
let user = {id:111,name:'user',password:123456}
delete user.password //置空密码
let token =sign(user,'123456',10);
// let token ='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTExLCJuYW1lIjoidXNlciIsImlhdCI6MTU5NTU5NzA0\n' +
//     'MCwiZXhwIjoxNTk1NTk3MDUwfQ.CJ5RdyGHwxj_7ib2BHn583e7dRNzEWcTiRfkiEVLwc8\n';
verify(token,'123456',function (user) {
    console.log(user)
})
console.log(token)*/
